#pragma once

#include"formatter.hpp"
#include<fstream>
namespace yd
{
    class log_sink
    {
        public:
        using ptr=std::shared_ptr<log_sink>;
        virtual ~log_sink(){}
        virtual void log(const char*data,size_t len)=0;
    };
    class StdoutSink:public log_sink
    {
        public:
        using ptr = std::shared_ptr<StdoutSink>;
        StdoutSink() = default;
        void log(const char*data,size_t len)
        {
            std::cout.write(data,len);
        }
    };
    class FileSink:public log_sink
    {
        public:
        FileSink( const std::string&filename):_filename(filename)
        {
            file::create_dir(file::path(filename));
            _ofs.open(_filename,std::ios::binary | std::ios::app);

        }
        void log(const char*data,size_t len)
        {
            _ofs.write(data,len);

        }
        private:
        std::ofstream _ofs;
        std::string _filename;
    };
    class RollSink:public log_sink
    {
        public:
        using ptr = std::shared_ptr<RollSink>;
        RollSink(const std::string &basename,size_t max_size)
        :_basename(basename)
        ,_max_size(max_size)
        ,_cur_size(0)
        {
            file::create_dir(file::path(basename));
        }
        void log(const char*data,size_t len)
        {
            initLogFile();
            _ofs.write(data,len);
            _cur_size+=len;
        }
        private:
        void initLogFile() {
            if (_ofs.is_open() == false || _cur_size >= _max_size) {
                _ofs.close();
                std::string name = createFilename();
                _ofs.open(name, std::ios::binary | std::ios::app);
                //assert(_ofs.is_open());
                _cur_size = 0;
                return;
            }
            return;
        } 
        std::string createFilename() {
            time_t t = time(NULL);
            struct tm lt;
            localtime_r(&t, &lt);
            std::stringstream ss;
            ss << _basename;
            ss << lt.tm_year + 1900;
            ss << lt.tm_mon + 1;
            ss << lt.tm_mday;
            ss << lt.tm_hour;
            ss << lt.tm_min;
            ss << lt.tm_sec;
            ss << ".log";
            return ss.str();
        }
        std::string _basename;
        std::ofstream _ofs;
        size_t _max_size;
        size_t _cur_size;
    };

    class factory
    {
        public:
        template<typename Sinktype,typename ...Args>
        static log_sink::ptr create(Args &&...args)
        {
            return std::make_shared<Sinktype>(std::forward<Args>(args)...);
        }
    };
}